﻿$import( "SmitearWebGL.Core.Geometry.Edge" );
$import( "SmitearWebGL.Core.Geometry.Vertex" );
$import( "SmitearWebGL.Core.Geometry.Uvt" );

SmitearWebGL.Core.Geometry.Triangle = Class.extend(
{
	/******** constructor ********/

	init : function( p0, p1, p2, uv0, uv1, uv2 )
	{
		/******** public property ********/
		
		this.p0 = p0;
		this.p1 = p1;
		this.p2 = p2;
		
		this.p0.correlativeFaces.push( this );
		this.p1.correlativeFaces.push( this );
		this.p2.correlativeFaces.push( this );
		
		this.uv0 = uv0;
		this.uv1 = uv1;
		this.uv2 = uv2;
		
		this.vertices = new Array( 3 );
		this.uvs = new Array( 3 );
		
		this.vertices[0] = this.p0;
		this.vertices[1] = this.p1;
		this.vertices[2] = this.p2;
		
		this.uvs[0] = uv0;
		this.uvs[1] = uv1;
		this.uvs[2] = uv2;

		this.normal = null;

		this._registClass( "SmitearWebGL.Core.Geometry.Triangle" );
	}
	,
	release : function()
	{
		this.vertices = null;
		this.uvs = null;
		this.p0 = null;
		this.p1 = null;
		this.p2 = null;
		
		this.uv0 = null;
		this.uv1 = null;
		this.uv2 = null;
		this.normal = null;
	}
	,
	clone : function()
	{
		return new SmitearWebGL.Core.Geometry.Triangle( this.p0.clone(), this.p1.clone(), this.p2.clone(), this.uv0.clone(), this.uv1.clone(), this.uv2.clone() );
	}
	,
	calculatNormal : function()
	{
		this.normal = SmitearWebGL.Core.Geometry.Triangle.calculatNormal( this.p0, this.p1, this.p2 );
	}
}
);

SmitearWebGL.Core.Geometry.Triangle.calculatNormal = function( p0, p1, p2, output )
{
	output = output || $V3();
	
	var vec0 = SmitearWebGL.Core.Geometry.Triangle.t_vec0;
	var vec1 = SmitearWebGL.Core.Geometry.Triangle.t_vec1;
	
	var p0x = p0.x;
	var p0y = p0.y;
	var p0z = p0.z;
	
	var p1x = p1.x;
	var p1y = p1.y;
	var p1z = p1.z;
	
	var p2x = p2.x;
	var p2y = p2.y;
	var p2z = p2.z;

	vec0.reset( p0x - p2x, p0y - p2y, p0z - p2z );
	vec1.reset( p0x - p1x, p0y - p1y, p0z - p1z );
	
	SmitearWebGL.Core.Math.Vector3.cross( vec1, vec0, output );
	output.normalize();
	
	return output;
}

SmitearWebGL.Core.Geometry.Triangle.t_vec0 = $V3();
SmitearWebGL.Core.Geometry.Triangle.t_vec1 = $V3();